package com.seesmic.methodgroups
{
	/*
	Copyright 2007 SEESMIC, Inc
	Licensed under the Apache License, Version 2.0 (the "License"); 
	you may not use this file except in compliance with the License. You may obtain a copy of the License at 
	
	http://www.apache.org/licenses/LICENSE-2.0 
	
	Unless required by applicable law or agreed to in writing, 
	software distributed under the License is distributed on an 
	"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
	See the License for the specific language governing permissions and limitations under the License.
	*/
	
	import com.seesmic.SeesmicError;
	import com.seesmic.ServiceBase;
	import com.seesmic.UserVO;
	import com.seesmic.VideoVO;
	import com.seesmic.events.SeesmicResultEvent;
	import com.seesmic.helper.URLLoaderBase;
	import com.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	
	public class MethodGroup extends EventDispatcher
	{
		public var service:ServiceBase
		public function MethodGroup(service:ServiceBase)
			{
			super();
			this.service = service
		}
		
		protected function  parse(object:*):Object
		{
			var loader:URLLoader = object as URLLoader;
			return	JSON.deserialize(loader.data)
		}
		
		protected function parseVideos(object:*):Array
		{
			var array:Array = new Array();
			for(var i:* in object)
			{
				var video:* = object[i]
				var videoVO:VideoVO = new VideoVO();
				videoVO.parse(video)
				array.push(videoVO)
			}
			return array
		}
		
		protected function parseUsers(object:*):Array
		{
			var array:Array = new Array();
			for(var i:* in object)
			{
				var user:* = object[i]
				var userVO:UserVO = new UserVO();
				userVO.parse(user)
				array.push(userVO)
			}
			return array
		}
		
		protected function isError(e:Event , type:String, additionalCheck:String = null):Boolean
		{
			trace("EVENT TYPE " + e.type + " FOR " + type)
			if(e is IOErrorEvent)
			{
				service.dispatchEvent(new SeesmicResultEvent(type, null, false, IOErrorEvent.IO_ERROR))
				return true;
			}
			else if(e is SecurityErrorEvent)
			{
				service.dispatchEvent(new SeesmicResultEvent(type, null, false, SecurityErrorEvent.SECURITY_ERROR))
				return true;
			}
			else if(e.type  == SeesmicError.TIME_OUT )
			{
				service.dispatchEvent(new SeesmicResultEvent(type, null, false, URLLoaderBase.TIME_OUT))
				return true;
			}
			else if(additionalCheck != null)
			{
				var obj:Object = parse(e.target)
				
				trace(obj.hasOwnProperty(additionalCheck))
				trace(typeof(obj[additionalCheck].success))
				if(obj.hasOwnProperty(additionalCheck) && obj[additionalCheck].success == 'false' )
				{
					service.dispatchEvent(new SeesmicResultEvent(type, null, false, obj[additionalCheck].reason))
					return true;
				}
			}
			 
			 return false
			 
		}
		
 

	}
}